<template>
	<div id="mind-map">
		<el-button type="primary" @click="horizontal = !horizontal"
			>切换tree方向</el-button
		>
		<!-- <el-button type="primary" @click="getData('http://wei45955.host:45955/data');">导入文件</el-button> -->

		<el-button type="primary" @click="downloadCurrentData()"
			>下载JSON数据文件</el-button
		>

		<el-button type="primary" @click="saveDataToService(newMap)"
			>保存文件到云端（简单完成）</el-button
		>

		<input type="text" id="inputNewMapName" />
		<input type="button" value="创建一个新图" @click="addNewMap()" />

		<div>
			<select
				name="selected"
				v-model="nowMap"
			>
				<option :value="eachMap" v-for="eachMap in mapList">
					{{ eachMap }}
				</option>
			</select>
			<span> 当前选择/添加： {{ newMap?newMap : nowMap }} </span>
		</div>

		<ul>
			<li v-for="eachMap in mapList">
				{{ eachMap }}
			</li>
		</ul>

		<org-tree
			id="orgTreeNode"
			:data="data"
			:horizontal="horizontal"
			collapsable
			:render-content="renderContent"
			@on-expand="onExpand"
			@on-node-mouseover="onMouseover"
			@on-node-mouseout="onMouseout"
			@on-expand-mouseover="Mouseover"
			@on-expand-mouseout="Mouseout"
		>
		
		<!--  上面删除了 @on-node-click="cccc" -->
		
		</org-tree>
		<div
			class="floating"
			v-show="isShowF && bd"
			@mouseover="
				() => {
					isShowF = true;
				}
			"
			@mouseout="
				() => {
					isShowF = false;
				}
			"
			@mousewheel.prevent="mouseWheelDia"
		>
			<span @click="addOrEdit(0)">增加</span>
			<span @click="addOrEdit(1)">编辑</span>
			<span @click="del">删除</span>
		</div>
		<!-- 增加/编辑弹层 -->
		<el-dialog
			title="提示"
			v-if="dialogVisible"
			:visible="dialogVisible"
			@close="clearDialog"
			show-close
			:close-on-click-modal="false"
			custom-class="addOrEditDia"
			width="35%"
		>
			<div class="tips">
				<el-form
					:model="ruleForm"
					:rules="rules"
					ref="ruleForm"
					class="demo-ruleForm"
					@submit.native.prevent
				>
					<el-form-item prop="partnerName">
						<el-input
							v-focus
							placeholder="请输入节点名称"
							:maxlength="100"
							clearable
							v-model="ruleForm.partnerName"
							@keyup.enter.native="confirm"
						></el-input>
					</el-form-item>
				</el-form>
			</div>
			<span slot="footer" class="dialog-footer">
				<div class="tip-left">
					<el-button
						size="small"
						type="info"
						@click="dialogVisible = false"
						>取消</el-button
					>
					<el-button size="small" type="primary" @click="confirm"
						>确定</el-button
					>
				</div>
			</span>
		</el-dialog>

		<!-- 删除 -->
		<el-dialog
			title="提示"
			v-if="dialogVisible2"
			:visible="dialogVisible2"
			@close="clearDialog"
			custom-class="delDia"
			width="35%"
		>
			<div class="tips">
				<p style="text-align: left">确定要删除该节点吗?</p>
			</div>
			<span slot="footer" class="dialog-footer">
				<div class="tip-left">
					<el-button
						size="mini"
						type="info"
						@click="dialogVisible2 = false"
						>取消</el-button
					>
					<el-button size="mini" type="primary" @click="confimdelete"
						>确定</el-button
					>
				</div>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import OrgTree from "./org-tree";
import axios from "axios";

export default {
	name: "MindMap",
	components: {
		OrgTree,
	},
	directives: {
		focus: {
			inserted: function (el) {
				el.querySelector("input").focus();
			},
		},
	},
	data() {
		return {
			bd: true,
			ruleForm: {
				partnerName: "",
			},
			rules: {
				partnerName: [
					{
						required: true,
						message: "请输入节点名称",
						trigger: "blur",
					},
				],
			},
			dialogVisible: false,
			dialogVisible2: false,
			isShowF: false,
			data: null,
			horizontal: true,
			collapsable: true,
			isEdit: 0,
			currentTreeData: {},
			lastId: 100,
			labelClassName: "bg-white",
			nowMap: null,
			mapList: null,
			newMap: null
		};
	},
	mounted() {
		this.getData("http://wei45955.host:45955/map/ALL", (gotData) => {
			this.mapList = gotData;
		});
	},

	watch: {
		dialogVisible: {
			handler(newV, oldV) {
				if (newV == false) {
					this.ruleForm.partnerName = "";
				}
			},
		},
		nowMap: function (newV) {
			this.getData(
				"http://wei45955.host:45955/map/" + newV,
				(gotData) => {
					this.data = gotData;
				}
			);
		},
	},

	methods: {
		// bugfix 鼠标移入弹层，滚动鼠标不能缩放bug
		mouseWheelDia() {
			this.isShowF = false;
		},

		// 鼠标移入缩放icon
		Mouseover() {
			this.bd = false;
		},

		// 鼠标移出缩放icon
		Mouseout() {
			this.bd = true;
		},

		// 关闭添加/编辑/删除弹层
		clearDialog() {
			this.dialogVisible = false;
			this.dialogVisible2 = false;
			this.ruleForm.partnerName = "";
		},

		// 点击添加/编辑
		addOrEdit(val) {
			// 新增val：0，编辑val：1
			this.dialogVisible = true;
			this.isEdit = val;
			// eslint-disable-next-line eqeqeq
			if (val == 1) {
				// 编辑回显
				this.ruleForm.partnerName = this.currentTreeData.label;
			}
		},

		// 添加/编辑的确定
		confirm() {
			this.$refs.ruleForm.validate((valid) => {
				if (valid) {
					const newdata = {
						label: this.ruleForm.partnerName,
						id: null,
						expand: true,
					};
					if (this.isEdit == 1) {
						this.currentTreeData.label = newdata.label;
						// 前端编辑数据
						this.$message({
							type: "success",
							message: "节点修改成功！",
						});
						this.clearDialog();
					} else {
						newdata.children = [];
						console.log(this.currentTreeData);
						this.currentTreeData.children.push(newdata);
					
						this.$message({
							type: "success",
							message: "新增节点成功！",
						});
						this.clearDialog();
					}
				}
			});
		},

		// 随机 ID 生成算法
		uuid() {
			var s = [];
			var hexDigits = "0123456789abcdef";
			for (var i = 0; i < 36; i++) {
				s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
			}
			s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
			s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
			s[8] = s[13] = s[18] = s[23] = "-";

			var uuid = s.join("");
			return uuid;
		},

		del() {
			this.dialogVisible2 = true;
		},

		// 是否确定删除当前节点
		confimdelete() {
			// 前端删除 遍历原数据,删除匹配id数据
			const deleteData = (data) => {
				data.some((item, i) => {
					if (item.id === this.currentTreeData.id) {
						data.splice(i, 1);
					} else if (item.children) {
						deleteData(item.children);
					}
				});
			};
			const arr = [this.data];
			deleteData(arr);
			this.data = arr[0] ? arr[0] : {};
			this.dialogVisible2 = false;
			this.$message({
				type: "success",
				message: "节点删除成功！",
			});
		},

		// 鼠标移入树节点
		onMouseover(e, data) {
			this.currentTreeData = data; // 鼠标移入，该节点的所有数据
			this.isShowF = true;
			var floating = document.getElementsByClassName("floating")[0];
			floating.style.left = e.clientX + "px";
			floating.style.top = e.clientY + "px";
		},

		// 鼠标移出树节点
		onMouseout(e, data) {
			this.isShowF = false;
		},

		renderContent(h, data) {
			return data.label;
		},

		// 节点展开收缩
		onExpand(e, data) {
			// eslint-disable-next-line eqeqeq
			if (data.expand == true) {
				// bugfix
				var dom = document.getElementById("ddd");
				(dom.style.top = "50%"), (dom.style.left = "8%");
			}
			if ("expand" in data) {
				data.expand = !data.expand;
				if (!data.expand && data.children) {
					this.collapse(data.children);
				}
			} else {
				this.$set(data, "expand", true);
			}
		},

		collapse(list) {
			list.forEach((child) => {
				if (child.expand) {
					child.expand = false;
				}

				child.children && this.collapse(child.children);
			});
		},

		// 节点默认全部展开
		toggleExpand(data, val) {
			var _this = this;
			if (Array.isArray(data)) {
				data.forEach(function (item) {
					_this.$set(item, "expand", val);
					if (item.children) {
						_this.toggleExpand(item.children, val);
					}
				});
			} else {
				this.$set(data, "expand", val);
				if (data.children) {
					_this.toggleExpand(data.children, val);
				}
			}
		},

		getData(desUrl, callback) {
			axios
				.get(desUrl)
				.then((response) => {
					callback(response.data);
				})
				.catch(function (error) {
					// 请求失败处理
					console.log(desUrl, error);
				});
		},

		download(content, fileName = "data.json", contentType = "text/json") {
			var a = document.createElement("a");
			content = JSON.stringify(content, undefined, "\t");
			var file = new Blob([content], { type: contentType });
			a.href = URL.createObjectURL(file);
			a.download = fileName;
			a.click();
		},

		downloadCurrentData() {
			this.download(this.data);
		},

		saveDataToService(newMapName) {
			// 如果不对 提前结束
			if(this.newMap != null && (document.getElementById("inputNewMapName").value != this.newMap) ){
				this.$message({
					type: "error",
					message: "保存图失败，因为当前输入框图名改变！",
				});
				this.clearDialog();
				return ;
			}
			axios
				.post(
					"http://wei45955.host:45955/map/" + newMapName,
					JSON.stringify(this.data, undefined, "\t")
				)
				.then((response) => {
					console.log("save successfully", response);
				})
				.catch(function (error) {
					console.log("save wrong", error);
				});
			this.$message({
				type: "success",
				message: "保存成功！",
			});
			this.clearDialog();	
			this.newMap = null;
		},

		addNewMap() {
			let newMapName = document.getElementById("inputNewMapName").value;
			console.log(newMapName);
			if (newMapName.length != 0) {
				this.newMap = newMapName;
				this.data = {
					id: null,
					label: newMapName,
					expand: true,
					children: [],
				};
			}
		},
	},
};
</script>

<style lang="less" scoped>
.floating {
	background: rgba(0, 0, 0, 0.7);
	box-shadow: rgba(0, 0, 0, 0.2);
	width: 130px;
	height: 45px;
	line-height: 45px;
	display: flex;
	justify-content: space-around;
	position: absolute;
	color: #fff;
	border-radius: 5px;
	box-sizing: border-box;
	left: 0;
	top: 0;
	transition: all 0.3s;
	z-index: 999;
	font-size: 12px;
	span {
		cursor: pointer;
	}
}
</style>
<style lang="less">
.addOrEditDia,
.delDia {
	padding: 14px 18px 10px 18px;
	border-radius: 4px !important;
	.el-dialog__header {
		display: flex;
		justify-content: space-between;
	}
	.el-dialog__body {
		margin-top: 37px;
	}
	.el-dialog__footer {
		padding: 27px 0 9px 0 !important;
	}
	.el-dialog__headerbtn {
		position: static !important;
	}
}
.bg-white {
	background-color: white;
}
.bg-orange {
	background-color: orange;
}
.bg-gold {
	background-color: gold;
}
.bg-gray {
	background-color: gray;
}
.bg-lightpink {
	background-color: lightpink;
}
.bg-chocolate {
	background-color: chocolate;
}
.bg-tomato {
	background-color: tomato;
}
</style>
